import subprocess
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class AndroidAudioPlayerLibrary:
    def __init__(self):
        logging.info("AndroidAudioPlayerLibrary 初始化完成。")

    def run_adb_command(self, command):
        """
        运行 ADB 命令并返回输出。

        :param command: 要执行的 ADB 命令
        :return: 命令的标准输出
        :raises: 如果命令执行失败，抛出异常并记录错误信息
        """
        logging.info(f"正在执行 ADB 命令: {command}")
        try:
            result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
            if result.returncode != 0:
                error_msg = f"ADB 命令执行失败: {result.stderr}"
                logging.error(error_msg)
                raise Exception(error_msg)
            logging.info(f"ADB 命令执行成功，输出: {result.stdout}")
            return result.stdout
        except Exception as e:
            logging.error(f"运行 ADB 命令时发生异常: {e}")
            raise

    def play_audio_file(self, device_file_path):
        """
        在安卓设备上播放指定的语音文件。

        :param device_file_path: 设备上语音文件的路径
        :raises: 如果播放失败，抛出异常并记录错误信息
        """
        logging.info(f"开始播放设备上的语音文件: {device_file_path}")
        try:
            command = f"adb shell am start -a android.intent.action.VIEW -d file://{device_file_path} -t audio/*"
            self.run_adb_command(command)
            logging.info(f"正在播放设备上的语音文件: {device_file_path}")
        except Exception as e:
            logging.error(f"播放语音文件失败: {e}")
            raise